﻿using Md.Api.Model.Util.IP.Request;

namespace Md.Util.Service.IP;
/// <summary>
/// IP是否在范围之内服务
/// 参考地址：https://blog.csdn.net/u012045045/article/details/102514535
/// </summary>
public class IsIPWithinRangeService : ApiBase<RequestIsIPWithinRangeModel>
{
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        if (string.IsNullOrWhiteSpace(Parameter.IPStr))
        {
            throw new AggregateException("IP不能为空");
        }

        if (string.IsNullOrWhiteSpace(Parameter.MaskStr))
        {
            throw new AggregateException("子网掩码不能为空");
        }

        string[] ips = Parameter.IPStr.Split(".");

        int ipAddr = (Convert.ToInt32(ips[0]) << 24) | (Convert.ToInt32(ips[1]) << 16) | (Convert.ToInt32(ips[2]) << 8) | Convert.ToInt32(ips[3]);

        int type = Convert.ToInt32(Parameter.MaskStr.Split("/")[1]);

        uint mask = 0xFFFFFFFF << (32 - type);

        string maskIp = Parameter.MaskStr.Split("/")[0];

        string[] maskIps = maskIp.Split(".");

        int cidrIpAddr = (Convert.ToInt32(maskIps[0]) << 24) | (Convert.ToInt32(maskIps[1]) << 16) | (Convert.ToInt32(maskIps[2]) << 8) | Convert.ToInt32(maskIps[3]);

        bool res = (ipAddr & mask) == (cidrIpAddr & mask);

        Result.Data = res;
        Result.Msg = "success";
    }
}
